//
//  CHTimerUtils.swift
//  nurseApp
//
//  Created by cyptt on 2022/8/10.
//

import UIKit
/*
 倒计时
 */
public class CHCountdownTimer: NSObject {

    
    private  var timer:Timer? = nil
    
    private var countDown_second:Int = 0
    
    private var countDown_result:Int = 0  //倒计时结构
    
    private  var countDown_i:Int = 0
    
    private var timeInterval:TimeInterval = 1  //间隔
    
    private  var countDowntResultB:((_ result:Int) -> ())?
    
    private  var countDowntendB:((_ result:Int) -> ())?
    
    public  override init(){
        super.init()
    }
    
    func start(){
        self.timer?.invalidate()
        self.timer = nil
        self.timer = Timer.scheduledTimer(timeInterval: self.timeInterval, target: self, selector: #selector(timerFunc), userInfo: nil, repeats: true)
        self.timer?.fire()
    }
    
    
    public  func countDowntResultBlock(clouse:@escaping (_ result:Int)->()){
        self.countDowntResultB = clouse
    }
    
    public  func countDowntimeEndBlock(clouse:@escaping (_ result:Int)->()){
        self.countDowntendB = clouse
    }
    
    /*
     倒计时
     */
    public func startCountDown(second:Int,timeInterval ti:TimeInterval = 1){
        
        self.timeInterval = ti
        self.countDown_second = second
        //倒计时
        if self.countDown_second != 0 {
            countDown_i = 0
            countDown_result = countDown_second
        }
        self.start()
    }
    
    public  func end(){
        self.timer?.invalidate()
        self.timer = nil
    }
    
}

extension CHCountdownTimer{
    @objc func timerFunc(){
        if self.countDown_result <= 0{
            if self.countDowntendB != nil{
                self.countDowntendB!(0)
            }
            self.end()
            return
        }
       
        countDown_result = countDown_second - countDown_i
        countDown_i =  countDown_i + Int(self.timeInterval)
        if self.countDowntResultB != nil{
            self.countDowntResultB!(countDown_result)
        }

    }
}


extension CHCountdownTimer {

}

